//消息对象模型
let messageModel = {
    code: 2,
    publisher: "",
    receiver: "",
    message: ""
};

$(function () {

    //创建一个websocket，并给他的消息接收回调赋值
    createAWebSocketBindOnMsg(indexMsgOnReceive);

    //获取消息的发送者
    messageModel.publisher = localStorage.getItem(USERNAME_KEY_LOGIN_LOCALSTORAGE);

    //绑定登出按键的点击事件
    $("#btn_logOut").click(loginOutBtnOnClick);


    //隐藏底部输入框
    $("#div_msgInput").hide();


    $("#btn_sendMsg").click(sendMsgBtnOnClick);

});

/**
 * 退出按键的点击
 */
function loginOutBtnOnClick() {


    let loginUserName = localStorage.getItem(USERNAME_KEY_LOGIN_LOCALSTORAGE);

    if (loginUserName != null) {
        let logoutResult = MyAjax(`${HOST_BACK}/logout`, "POST", {username: loginUserName});
        alert(logoutResult.msg);
        localStorage.clear();
    }
    location.href = "/html/message/login.html";

}

/**
 * index页面的消息接收
 */
function indexMsgOnReceive(event) {
    // console.log("方法indexMsgOnReceive中的 event = ", event);
    // let data = event.data;

    //将data的JSON字符串转为data对象
    let data = JSON.parse(event.data);

    // console.log("方法indexMsgOnReceive中的 data=", data);
    // console.log("方法indexMsgOnReceive中的 data.code=", data.code);
    // console.log("方法indexMsgOnReceive中的 data.[\"code\"]=", data["code"]);

    switch (data.code) {
        //有用户上线
        case 0:
            updateOnlineUserList(data.message);
            break;
        //有用户下线
        case 1:
            break;
        //用户发送给用户消息
        case 2:
            console.log("有用户发送消息！data==", data);
            updateChatList(data);
            break;

    }
}


/**
 * 更新在线用户
 * @param onlineUsers
 */
function updateOnlineUserList(onlineUsers = []) {

    //获取登录的用户名
    let curLoginUsername = localStorage.getItem(USERNAME_KEY_LOGIN_LOCALSTORAGE);


    let userListHtml = "";

    onlineUsers.forEach((username) => {

        if (curLoginUsername != username) {
            userListHtml += ` 
             <tr>
                <td>${username}</td>
                <td><font color="green">在线</font></td>
                <td><a href="javascript:void(0);" onclick="chatBtnOnClick('${username}')">聊天</a></td>
                <td><font id="ft_${username}" value="0" color="#a9a9a9">*</font></td>
         </tr>`
        }
    });
    $("#tbody_registerUsers").html(userListHtml);

}

/**
 * 聊天按键的点击事件
 * @param chatObjName
 */
function chatBtnOnClick(chatObjName = "") {

    //赋值消息我的接收者
    messageModel.receiver = chatObjName;

    //如果被点击的用户有消息发送过来，且没接收
    if ($(`#ft_${chatObjName}`).val() == 1) {
        $(`#ft_${chatObjName}`).val(0);
        $(`#ft_${chatObjName}`).css("color", "#a9a9a9");
    }


    $("#talkTitle").html(`正在与<font color="blue">${chatObjName}</font>聊天`)

    //显示输入框
    $("#div_msgInput").show();

}


/**
 * 发送消息按键点击事件
 */
function sendMsgBtnOnClick() {

    let sendMsg = $("#toSendMsg").val();

    if (sendMsg == null || "" == (sendMsg.replace(" ", ""))) {

        alert("发送的消息不能为空！");
        return;
    }

    //赋值需要发送的消息
    messageModel.message = sendMsg;


    let retData = MyAjax(`${HOST_BACK}${SERVICE_MSG}`, "POST", messageModel);

    if (retData.msg == "success") {
        // alert("消息发送成功！");

        //TODO 页面回显发送的消息

        updateChatList(messageModel);


        //清空消息框
        $("#toSendMsg").val("");

    } else {
        alert(retData.msg);
    }


}


/**
 * 更新聊天列表
 */
function updateChatList(message = {}) {


    let appendHtml = '';

    //如果登录用户为发送消息的用户，消息应该显示在右边
    if (message.publisher == messageModel.publisher) {

        appendHtml = `<div class="Dialog-parent-right">
            
            <div class="alertDialog-right">${message.message}</div>
            <div class="Dialog-head">${message.publisher}</div>
            </div>`
    }
    //如果当前用户为接收者时
    else {

        //如果当前登录用户聊天对象不是消息的发布者，直接返回
        if (messageModel.receiver != message.publisher) {

            $(`#ft_${message.publisher}`).val(1);
            $(`#ft_${message.publisher}`).css("color", "red");

            return;
        }

        appendHtml = `<div class="Dialog-parent-left ">
         
          <div class="Dialog-head">${message.publisher}</div>
            <div class="alertDialog-left">${message.message}</div>

            </div>`
    }

    $("#chatList").append(appendHtml);
}